package com.hht;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author hht
 * @Description //TODO
 * @Date 15:47 2019/2/18
 * @Param
 * @return
 **/
public class AtomDemo {

	public static void main(String[] args) {
		
		new ANT().start();
		new ANT().start();
		new ANT().start();
		new ANT().start();
	}
}

class AData {
	//用原子操作代替锁的机制
	static AtomicInteger ai = new AtomicInteger(0);
	static int i = 0;

	static void operate() {
		//基于cas原理实现 compare  and set，有一定的的性能损耗，但很低
		System.out.println("atom :"+ai.incrementAndGet());
		//对比代码
//		System.out.println("int :"+i++);
	}
}

class ANT extends Thread {
	public void run() {
		while(true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			AData.operate();
		}
	}
}
